package com.frcdi.qms.utils;

import com.frcdi.qms.common.core.domain.entity.SysRole;
import com.frcdi.qms.common.core.domain.model.LoginUser;
import com.frcdi.qms.common.utils.SecurityUtils;
import com.frcdi.qms.common.utils.ip.IpUtils;
import com.frcdi.qms.system.domain.SysUserOperLog;
import com.frcdi.qms.system.service.ISysDeptService;
import com.frcdi.qms.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能描述
 *
 * @author: author
 * @date: 2023年08月31日 11:35
 */
@Component
public class LogManage {
    @Autowired
    private  ISysDeptService deptService;

    @Autowired
    private ISysRoleService roleService;

    private static LogManage logManage;

    @PostConstruct
    public void init() {
        logManage = this;
        logManage.deptService = this.deptService;
        logManage.roleService = this.roleService;
    }
    private static SysUserOperLog log=null;

    public static SysUserOperLog getLog(String modelName, String tableName, Integer Type) {
        log = new SysUserOperLog();
        log.setModelName(modelName);
        log.setTableName(tableName);
        log.setType(Type);
        LoginUser loginUser = SecurityUtils.getLoginUser();
        log.setOperId(loginUser.getUsername());
        log.setOperName(loginUser.getUser().getNickName());
        log.setDeptName(logManage.deptService.getDeptName(loginUser.getDeptId()));
        log.setOperIp(IpUtils.getIpAddr());
        List<String> roles = logManage.roleService.selectRolesByUserId(loginUser.getUserId()).stream().map(SysRole::getRoleName).collect(Collectors.toList());
        log.setOperRoles(String.valueOf(roles));

        return log;
    }

    public static SysUserOperLog getNoUserLog(String modelName, String tableName, Integer Type) {
        log = new SysUserOperLog();
        log.setModelName(modelName);
        log.setTableName(tableName);
        log.setType(Type);
        log.setOperId("系统");
        log.setOperName("系统");
        log.setDeptName("系统");
        log.setOperIp("内网IP");
        log.setOperRoles("系统");
        return log;
    }
}
